package com.sh.shanhuo.filter;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;


/**
 * 自定义输入框限制字数
 */
public class TextInputFilter implements InputFilter {
    private int length;
    private boolean isMax;
    private Context context;

    public TextInputFilter(boolean isMax, int length, Context context) {
        this.length = length;
        this.isMax = isMax;
        this.context = context;
    }

    public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                               int dstart, int dend) {
        int MAX;
        if (isMax) {
            MAX = length - (dest.length() - (dend - dstart));
        } else {
            MAX = (dest.length() - (dend - dstart)) - length;
        }
        if (MAX <= 0) {
            //这里，用来给用户提示
            if (isMax) {
                Toast.makeText(context, "已超过最大字数限制", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "密码不足" + length + "位", Toast.LENGTH_SHORT).show();
            }
            return "";
        } else if (MAX >= end - start) {
            return null; // keep original
        } else {
            MAX += start;
            if (Character.isHighSurrogate(source.charAt(MAX - 1))) {
                --MAX;
                if (MAX == start) {
                    return "";
                }
            }
            return source.subSequence(start, MAX);
        }
    }

    /**
     * @return the maximum length enforced by this input filter
     */
    public int getLength() {
        return length;
    }
}
